function varargout = TLSstoolDlg(action,varargin)

% TL_SSTOOL_DLG manages user interface for TargetLink State Space Tool
%
% SYNTAX dlgInfo = TLSstoolDlg('GetDlgInfo');
%   gets dialog info of TargetLink State Space Tool
%
%   INPUT ARGUMENTS
%   -/-
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLSstoolDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLSstoolDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLSstoolDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLSstoolDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLSstoolDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit
% $RCSfile: TLSstoolDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/ProdCodeGen/L1Scaler/Sources/MSrc/project.pj $
% $Revision: 1.12 $
% $Date: 2011/04/11 10:47:23MESZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action
    case 'GetDlgInfo'
        dlgInfo = tl_get_dlginfodefaults('tltool');
        dlgInfo.pageNames = {'Scaling'};
        dlgInfo.title     = 'State-Space Scaling Tool';
        varargout = {dlgInfo};
        
    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        switch pageName
            case 'Scaling'
                [sheetDims,ctrlPos] = FcnCalcScalingControlPositions(commonGeom);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;
        
    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName,dlgdata.pageNames,'exact');
        switch pageName
            case 'Scaling'
                dlgdata = FcnCreateScalingPage(pageNum,dlgfig,dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;
        
    case 'Manage'
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName,dlgdata.pageNames,'exact');
        
        switch pageName
            case 'Scaling'
                [dlgdata, bModified] = FcnManageScalingPage(pageNum,dlgfig,dlgdata,pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified;
        
    case 'SystemButtons'
        dlgfig  = varargin{1};
        dlgdata = varargin{2};
        Action  = varargin{3};
        
        bModified = false;
        
        switch Action
            case 'PlotResults'
                if ~dlgdata.toolData.bIsScaled
                    errordlg('Please perform L1-scaling procedure.','Help','modal');
                else
                    if ~ishandle(dlgdata.toolfig)
                        pageNum = 1;
                        % get data from current dialog
                        data = FcnsetPlotData(dlgdata);
                        set(dlgfig,'Pointer','watch');
                        % open plot figure
                        dlgdata.toolfig = tl_open_toolfig( ...
                            dlgdata.pageData{pageNum}.model,dlgdata.maskType,data);
                        set(dlgfig,'Pointer','arrow');
                        bModified = true;
                    else
                        figure(dlgdata.toolfig);
                    end
                end
        end
        
        varargout{1} = dlgdata;
        varargout{2} = bModified;
        
    case 'titlechange'
        toolFig = varargin{1};
        pageNum = 1;
        
        dlgdata = get(toolFig,'Userdata');
        block   = dlgdata.pageData{pageNum}.model;
        figdata.block = get_param(block,'Name');
        name = ['TargetLink: State-Space Scaling Tool for ''' figdata.block ''''];
        set(toolFig,'Name',name);
        
        if ishandle(dlgdata.toolfig)
            name = ['TargetLink: Worst Case Signals for ''' figdata.block ''''];
            set(dlgdata.toolfig,'Name',name);
        end
        
    case 'UpdateData'
        dlgfig  = varargin{1};
        data    = varargin{2};
        pageNum = 1;
        
        dlgdata = get(dlgfig,'Userdata');
        dlgdata.pageData{pageNum}.origData = data;
        %tldlg('EnableRevert',dlgfig);
        dlgdata = FcnUpdateScalingPage(dlgdata,dlgfig,pageNum);
        if FcnChkOffsetAndType(dlgdata,1);
            set(dlgdata.SystemButtons.StatusLabel,'String','Ready', ...
                'ForegroundColor','k');
        end
        set(dlgfig,'Userdata',dlgdata);
        if ishandle(dlgdata.toolfig)
            FcnRefreshSSTool(dlgfig,dlgdata);
        end
        
    case 'Update' % empty case because of update of simulation plots
        dlgdata = varargin{2};
        varargout{1} = dlgdata;
        
    case 'Delete'
        dlgdata = get(gcbf,'Userdata');
        if isstruct(dlgdata) && ishandle(dlgdata.toolfig)
            delete(dlgdata.toolfig);
            dlgdata.toolfig = -1;
            set(gcbf,'Userdata',dlgdata);
        end
        
    otherwise
        error(['Invalid action "' action '"']);
        
end


%-----------------------------------------------------------------------------------------
% FcnCreateScalingPage creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateScalingPage(pageNum,dlgfig,dlgdata)

ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;

% delete function to close toolfig
set(dlgfig,'DeleteFcn','TLSstoolDlg(''Delete'');');

% save listbox data for subfunction FcnallignStrings
dlgdata.pageData{pageNum}.scalingListboxGeom = ctrlPos.scalingListboxGeom;
dlgdata.pageData{pageNum}.inputListboxGeom = ctrlPos.inputListboxGeom;
% save model handle in pageData
dlgdata.pageData{pageNum}.model = dlgdata.model;
dlgdata.model = -1;

% 'Output % State' groupbox and uicontrols
Children.scalingGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Output & State'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.scalingGroupbox);

Children.scalingListbox = uicontrol( ...
    'BackGroundColor',    'w', ...
    'FontName',           'Arial', ...
    'Min',                0, ...
    'Max',                2, ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'listbox', ...
    'Position',           ctrlPos.scalingListbox);

Children.varLabel = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'String',             'Var.', ...
    'Position',           ctrlPos.varLabel);
Children.numLabel1 = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'String',             'L1-scaling', ...
    'Position',           ctrlPos.numLabel1);
Children.numLabel2 = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'String',             'lower', ...
    'Position',           ctrlPos.numLabel2);
Children.numLabel3 = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'String',             'upper', ...
    'Position',           ctrlPos.numLabel3);
Children.numLabel4 = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'String',             'lower', ...
    'Position',           ctrlPos.numLabel4);
Children.numLabel5 = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'String',             'upper', ...
    'Position',           ctrlPos.numLabel5);
Children.numLabel6 = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'String',             'LSB', ...
    'Position',           ctrlPos.numLabel6);
Children.numLabel7 = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'String',             'Offset', ...
    'Position',           ctrlPos.numLabel7);
Children.numLabel8 = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'String',             'convergent', ...
    'Position',           ctrlPos.numLabel8);

Children.limitsLabel1 = uicontrol( ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'String',             'Constrained limits', ...
    'Position',           ctrlPos.limitsLabel1);
Children.limitsLabel2 = uicontrol( ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'String',             'Implemented limits', ...
    'Position',           ctrlPos.limitsLabel2);

Children.boldStateLabel = uicontrol( ...
    'FontWeight',         'bold', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'text', ...
    'Position',           ctrlPos.boldStateLabel);
Children.minConstrEdit = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','right', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'edit', ...
    'Position',           ctrlPos.minConstrEdit);
Children.maxConstrEdit = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','right', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'edit', ...
    'Position',           ctrlPos.maxConstrEdit);
Children.l1Popup = uicontrol( ...
    'BackGroundColor',    'w', ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'popup', ...
    'String',             {'yes' 'no'}, ...
    'Position',           ctrlPos.l1Popup);
% pushbutton
Children.l1ScaleButton = uicontrol( ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'pushbutton', ...
    'String',             'Scale', ...
    'Position',           ctrlPos.l1ScaleButton);
Children.l1ContinueButton = uicontrol( ...
    'Parent',             Children.scalingGroupbox, ...
    'Style',              'pushbutton', ...
    'String',             'Continue', ...
    'Position',           ctrlPos.l1ContinueButton);

% 'System Info' groupbox and uicontrols
Children.infoGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'System Info'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.infoGroupbox);

Children.stabilityLabel = uicontrol( ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'String',          'Stability:', ...
    'Position',        ctrlPos.stabilityLabel);
Children.numInputsLabel = uicontrol( ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'String',          'Num. of inputs:', ...
    'Position',        ctrlPos.numInputsLabel);
Children.numStatesLabel = uicontrol( ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'String',          'Num. of states:', ...
    'Position',        ctrlPos.numStatesLabel);
Children.typeStatesLabel = uicontrol( ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'String',          'Type of states:', ...
    'Position',        ctrlPos.typeStatesLabel);
Children.numOutputsLabel = uicontrol( ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'String',          'Num. of outputs:', ...
    'Position',        ctrlPos.numOutputsLabel);
Children.typeOutputsLabel = uicontrol( ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'String',          'Type of outputs:', ...
    'Position',        ctrlPos.typeOutputsLabel);

Children.stabilityInfoLabel = uicontrol( ...
    'FontWeight',      'bold', ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'Position',        ctrlPos.stabilityInfoLabel);
Children.numInputsInfoLabel = uicontrol( ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'Position',        ctrlPos.numInputsInfoLabel);
Children.numStatesInfoLabel = uicontrol( ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'Position',        ctrlPos.numStatesInfoLabel);
Children.typeStatesInfoLabel = uicontrol( ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'Position',        ctrlPos.typeStatesInfoLabel);
Children.numOutputsInfoLabel = uicontrol( ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'Position',        ctrlPos.numOutputsInfoLabel);
Children.typeOutputsInfoLabel = uicontrol( ...
    'Parent',          Children.infoGroupbox, ...
    'Style',           'text', ...
    'Position',        ctrlPos.typeOutputsInfoLabel);

% 'Scaling Options' groupbox and uicontrols
Children.optionsGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Scaling Options'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.optionsGroupbox);

Children.methodLabel = uicontrol( ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'text', ...
    'String',           'Scaling method:', ...
    'Position',         ctrlPos.methodLabel);
Children.convTolLabel = uicontrol( ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'text', ...
    'String',           'L1 convergence tolerance:', ...
    'Position',         ctrlPos.convTolLabel);
Children.maxRecLabel = uicontrol( ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'text', ...
    'String',           'Maximum computation time:', ...
    'Position',         ctrlPos.maxRecLabel);
Children.actRecLabel = uicontrol( ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'text', ...
    'String',           'Number of recursions:', ...
    'Position',         ctrlPos.actRecLabel);
Children.contLabel = uicontrol( ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'text', ...
    'String',           'Number of continuations:', ...
    'Position',         ctrlPos.contLabel);

Children.methodInfoLabel = uicontrol( ...
    'FontWeight',       'bold', ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'text', ...
    'String',           'L1-scaling', ...
    'Position',         ctrlPos.methodInfoLabel);
Children.convTolEdit = uicontrol( ...
    'BackgroundColor',  'w', ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'edit', ...
    'Position',         ctrlPos.convTolEdit);
Children.percLabel = uicontrol( ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'text', ...
    'String',           ' %', ...
    'Position',         ctrlPos.percLabel);
Children.maxTimeEdit = uicontrol( ...
    'BackgroundColor',  'w', ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'edit', ...
    'Position',         ctrlPos.maxTimeEdit);
Children.secLabel = uicontrol( ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'text', ...
    'String',           ' sec', ...
    'Position',         ctrlPos.secLabel);
Children.numRecInfoLabel = uicontrol( ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'text', ...
    'Position',         ctrlPos.numRecInfoLabel);
Children.contInfoLabel = uicontrol( ...
    'Parent',           Children.optionsGroupbox, ...
    'Style',            'text', ...
    'Position',         ctrlPos.contInfoLabel);

% 'Input' groupbox and uicontrols
Children.inputGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Input'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.inputGroupbox);

Children.inputListbox = uicontrol( ...
    'BackGroundColor',    'w', ...
    'FontName',           'Arial', ...
    'Min',                0, ...
    'Max',                2, ...
    'Parent',             Children.inputGroupbox, ...
    'Style',              'listbox', ...
    'String',             '  ', ...
    'Position',           ctrlPos.inputListbox);

Children.inputLabel = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.inputGroupbox, ...
    'Style',              'text', ...
    'String',             'Var.', ...
    'Position',           ctrlPos.inputLabel);
Children.maxInputLabel = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.inputGroupbox, ...
    'Style',              'text', ...
    'String',             'lower', ...
    'Position',           ctrlPos.maxInputLabel);
Children.minInputLabel = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.inputGroupbox, ...
    'Style',              'text', ...
    'String',             'upper', ...
    'Position',           ctrlPos.minInputLabel);
Children.limitsLabel3 = uicontrol( ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.inputGroupbox, ...
    'Style',              'text', ...
    'String',             'Constrained limits', ...
    'Position',           ctrlPos.limitsLabel3);
Children.boldInputLabel = uicontrol( ...
    'FontWeight',         'bold', ...
    'HorizontalAlignment','center', ...
    'Parent',             Children.inputGroupbox, ...
    'Style',              'text', ...
    'Position',           ctrlPos.boldInputLabel);

Children.minInputEdit = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','right', ...
    'Parent',             Children.inputGroupbox, ...
    'Style',              'edit', ...
    'Position',           ctrlPos.minInputEdit);
Children.maxInputEdit = uicontrol( ...
    'BackGroundColor',    'w', ...
    'HorizontalAlignment','right', ...
    'Parent',             Children.inputGroupbox, ...
    'Style',              'edit', ...
    'Position',           ctrlPos.maxInputEdit);

Dd = tl_resolve(dlgdata.data.dmatrix.value, dlgdata.pageData{1}.model);
numInputs = size(Dd, 2);
if numInputs
    enableStr = 'on';
    uiColor1  = [1 1 1];
    v = 1;
else
    enableStr = 'inactive';
    uiColor1  = get(dlgfig,'Color');
    v = [];
end
set(Children.inputListbox, ...
    'Enable',enableStr, ...
    'Value',v);
set(Children.minInputEdit, ...
    'Enable',enableStr, ...
    'BackgroundColor',uiColor1);
set(Children.maxInputEdit, ...
    'Enable',enableStr, ...
    'BackgroundColor',uiColor1);
set(Children.inputLabel, ...
    'BackgroundColor',uiColor1);
set(Children.maxInputLabel, ...
    'BackgroundColor',uiColor1);
set(Children.minInputLabel, ...
    'BackgroundColor',uiColor1);

Ad = tl_resolve(dlgdata.data.amatrix.value, dlgdata.pageData{1}.model);
numStates = size(Ad, 1);
if numStates
    enableStr = 'on';
    uiColor2  = [1 1 1];
else  % if system is a gain matrix
    enableStr = 'inactive';
    uiColor2  = get(dlgfig,'Color');
end
set(Children.convTolEdit, ...
    'Enable',enableStr, ...
    'BackGroundColor',uiColor2);
set(Children.maxTimeEdit, ...
    'Enable',enableStr, ...
    'BackGroundColor',uiColor2);

dlgdata.pageData{pageNum}.children = Children;

% save original data
dlgdata.pageData{pageNum}.origData = dlgdata.data;

% get tool data from parent dialog
parentData = get(dlgdata.parentfig,'UserData');
parentPageNum = parentData.CurrentPageNum;
dlgdata.toolData = parentData.pageData{parentPageNum}.toolData;

% initialize data
dlgdata = FcnInitScalingData(dlgdata);

% update scaling page
dlgdata = FcnUpdateScalingPage(dlgdata,dlgfig,pageNum);


%-----------------------------------------------------------------------------------------
% FcnManageScalingPage manage control actions of scaling page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageScalingPage(pageNum,dlgfig,dlgdata,pageAction)

bModified = true;
bRefresh = false;
Children  = dlgdata.pageData{pageNum}.children;

switch pageAction
    case 'scalingListbox'
        % get state/output information and write them into lower uicontrols
        v = get(Children.scalingListbox,'Value');
        FcnsetCtrlFields(dlgdata,pageNum,'scalingListbox',v);
        
    case 'inputListbox'
        % get input information and write them into lower uicontrols
        v = get(Children.inputListbox,'Value');
        FcnsetCtrlFields(dlgdata,pageNum,'inputListbox',v);
        
    case 'l1Popup'
        % change string in listbox
        v = get(Children.l1Popup,'Value');
        if v == 1
            bL1 = 1;
        else
            bL1 = 0;
        end
        v = get(Children.scalingListbox,'Value');
        dlgdata.toolData.bL1(v) = bL1;
        FcnsetCtrlFields(dlgdata,pageNum,'scalingListbox',v);
        bModified = true;
        bRefresh = true;
        
    case {'minConstrEdit' 'maxConstrEdit'}
        % write data to structure and update listbox
        v = get(Children.scalingListbox,'Value');
        h = [Children.minConstrEdit ...
            Children.maxConstrEdit];
        Ad = tl_resolve(dlgdata.data.amatrix.value, dlgdata.pageData{1}.model);
        numStates = size(Ad, 1);
        vx = v(v <= numStates);
        vy = v(v > numStates);
        if ~isempty(vx)
            minVar = dlgdata.data.state.min(vx);
            maxVar = dlgdata.data.state.max(vx);
        else
            minVar = [];
            maxVar = [];
        end
        if ~isempty(vy)
            minVar = ...
                [minVar dlgdata.data.output.min(vy-numStates)];
            maxVar = ...
                [maxVar dlgdata.data.output.max(vy-numStates)];
        end
        if strcmp(pageAction,'minConstrEdit')
            varStr = 'min';
            [minVarEdit,bModified] = FcnchkInput(h(1),'double');
            if ( bModified && ~isnan(minVarEdit) )
                if any(minVarEdit >= maxVar)
                    bModified = false;
                end
            end
        else
            varStr = 'max';
            [maxVarEdit,bModified] = FcnchkInput(h(2),'double');
            if ( bModified && ~isnan(maxVarEdit) )
                if any(maxVarEdit <= minVar)
                    bModified = false;
                end
            end
        end
        if bModified
            dlgdata.toolData.bConstr(v) = 1;
            %      dlgdata.toolData.bConstr(v) = all(~isnan([minVar maxVar]));
            if ~isempty(vx)
                eval(['dlgdata.data.state.' varStr '(vx) = ' varStr 'VarEdit;']);
            end
            if ~isempty(vy)
                eval(['dlgdata.data.output.' varStr '(vy-numStates) = ' varStr 'VarEdit;']);
            end
            dlgdata.toolData.bL1(v) = 0;
        else
            fprintf('');
        end
        FcnsetCtrlFields(dlgdata,pageNum,'scalingListbox',v);
        bRefresh = true;
        
    case {'minInputEdit' 'maxInputEdit'}
        % update listbox
        v = get(Children.inputListbox,'Value');
        h = [Children.minInputEdit ...
            Children.maxInputEdit];
        minVar = dlgdata.toolData.input.min;
        maxVar = dlgdata.toolData.input.max;
        if strcmp(pageAction,'minInputEdit')
            varStr = 'min';
            [minInput,bModified] = FcnchkInput(h(1),'double');
            if ( bModified && ~isnan(minInput) )
                if any(minInput > maxVar(v))
                    bModified = false;
                end
            end
        else
            varStr = 'max';
            [maxInput,bModified] = FcnchkInput(h(2),'double');
            if ( bModified && ~isnan(maxInput) )
                if any(maxInput < minVar(v))
                    bModified = false;
                end
            end
        end
        if bModified
            eval(['dlgdata.toolData.input.' varStr '(v) = ' varStr 'Input;']);
            if dlgdata.toolData.bIsScaled
                dlgdata.data.state.min  = dlgdata.data.state.min;
                dlgdata.data.state.max  = dlgdata.data.state.max;
                dlgdata.data.output.min = dlgdata.data.output.min;
                dlgdata.data.output.max = dlgdata.data.output.max;
                dlgdata.toolData.bIsScaled = 0;
                dlgdata = FcnInitScalingData(dlgdata);
            end
        else
            fprintf('');
        end
        % close plot figure, if it is open
        if ishandle(dlgdata.toolfig)
            ds_error_msg({'You have modified the input bounds.', ...
                'The Plot figure for Worst Case Signals will', ...
                'be closed and the scaling results will be cleared.'}, ...
                'Title','State-Space Scaling Tool', ...
                'PrintMessage','no', ...
                'RegisterMessage','no');
            delete(dlgdata.toolfig);
            dlgdata.toolfig = -1;
        end
        
        FcnsetCtrlFields(dlgdata,pageNum,'inputListbox',v);
        % update page
        bModified = true;
        
    case 'convTolEdit'
        % write convergence tolerance into structure
        oldConvTol = str2double(dlgdata.toolData.options.convTol);
        [convTol,bModified] = FcnchkInput(Children.convTolEdit,'double',oldConvTol);
        % check convergence tolerance
        if ( convTol < 0 || convTol > 100 )
            bModified = false;
        end
        if bModified
            dlgdata.toolData.options.convTol = sprintf('%0.3g',convTol);
            bIsScaled = dlgdata.toolData.bIsScaled;
            if ( bIsScaled && convTol < oldConvTol )
                converge_x = dlgdata.pageData{pageNum}.l1_strct.converge_x;
                converge_x = zeros(size(converge_x));
                converge_y = dlgdata.pageData{pageNum}.l1_strct.converge_y;
                converge_y = zeros(size(converge_y));
                dlgdata.pageData{pageNum}.l1_strct.converge_x = converge_x;
                dlgdata.pageData{pageNum}.l1_strct.converge_y = converge_y;
            end
        else
            fprintf('');
            set(gcbo,'String',sprintf('%0.3g',oldConvTol));
        end
        
    case 'maxTimeEdit'
        % write maximum number of recursions into structure
        oldMaxTime = str2double(dlgdata.toolData.options.maxTime);
        [maxTime,bModified] = FcnchkInput(Children.maxTimeEdit,'double',oldMaxTime);
        if maxTime < 0
            bModified = false;
        end
        if bModified
            dlgdata.toolData.options.maxTime = sprintf('%0.3g',maxTime);
        else
            fprintf('');
            set(gcbo,'String',sprintf('%0.3g',oldMaxTime));
        end
        
    case {'l1ScaleButton' 'l1ContinueButton'}
        bL1Scale = 1;
        u_min = dlgdata.toolData.input.min;
        u_max = dlgdata.toolData.input.max;
        if ~all(u_min<=u_max)
            v = find(~(u_min<=u_max));
            bL1Scale = 0;
            set(Children.inputListbox,'Value',v(1));
            FcnsetCtrlFields(dlgdata,pageNum,'inputListbox',v(1));
            ds_error_msg({['Element min u(' num2str(v(1)) ') must be less'] ...
                ['or equal than element max u(' num2str(v(1)) ').']}, ...
                'Title','State-Space Scaling Tool', ...
                'PrintMessage','no', ...
                'RegisterMessage','no');
        end
        
        if bL1Scale
            set(dlgfig,'Pointer','watch');
            % get data
            a_d = tl_resolve(dlgdata.data.amatrix.value, dlgdata.pageData{1}.model);
            b_d = tl_resolve(dlgdata.data.bmatrix.value, dlgdata.pageData{1}.model);
            c_d = tl_resolve(dlgdata.data.cmatrix.value, dlgdata.pageData{1}.model);
            d_d = tl_resolve(dlgdata.data.dmatrix.value, dlgdata.pageData{1}.model);
            numStates = size(a_d, 1);
            x0 = tl_resolve(dlgdata.data.state.initial, dlgdata.pageData{1}.model);
            if length(x0) == 1
                x0 = x0*ones(1,numStates);
            end
            maxTime = tl_resolve(dlgdata.toolData.options.maxTime, dlgdata.pageData{1}.model);
            convTol = tl_resolve(dlgdata.toolData.options.convTol, dlgdata.pageData{1}.model) / 100;
            
            % invoke/continue l1-algorithm
            if strcmp(pageAction,'l1ContinueButton')
                l1_strct = dlgdata.pageData{pageNum}.l1_strct;
                bIsContinued = 1;
                status_str = 'Continue';
            else
                l1_strct = [];
                bIsContinued = 0;
                status_str = 'Performing';
            end
            set(dlgdata.SystemButtons.StatusLabel,'String', ...
                [status_str ' L1-scaling ...'], ...
                'ForegroundColor','k');
            drawnow;
            [x_min,x_max,y_min,y_max,l1_strct] = tl_l1_norm(a_d,b_d,c_d,d_d, ...
                u_min',u_max',x0',[],[],[],[],maxTime,convTol,l1_strct);
            if isempty([x_min' x_max' y_min' y_max'])
                return;
            end
            
            % calculate state scaling parameters and write them into structure
            dlgdata.toolData.state.min = x_min';
            dlgdata.toolData.state.max = x_max';
            % calculate output scaling parameters and write them into structure
            dlgdata.toolData.output.min = y_min';
            dlgdata.toolData.output.max = y_max';
            
            dlgdata.toolData.bIsScaled = 1;
            dlgdata.pageData{pageNum}.l1_strct = l1_strct;
            
            if isempty(l1_strct) % if only gain matrix has been scaled
                dlgdata.toolData.options.numRecs = 1;
            else
                dlgdata.toolData.options.numRecs = ...
                    max(l1_strct.num_recs);
                if ( all(all(l1_strct.converge_x)) && all(all(l1_strct.converge_y)) )
                    maxActTol = sprintf('%0.4g',l1_strct.max_act_tol*100);
                    dlgdata.toolData.options.convTol = maxActTol;
                end
            end
            if bIsContinued
                contNum = dlgdata.toolData.options.contNum;
                contNum = contNum + 1;
            else
                contNum = 0;
            end
            dlgdata.toolData.options.contNum = contNum;
            if FcnChkOffsetAndType(dlgdata,0)
                set(dlgdata.SystemButtons.StatusLabel,'String', ...
                    [status_str ' L1-scaling ... done'], ...
                    'ForegroundColor','k');
            end
            
            set(dlgfig,'Pointer','arrow');
            bModified = true;
            bRefresh = true;
        else
            bRefresh = false;
            bModified = false;
        end
end


if bModified
    dlgdata = FcnUpdateScalingPage(dlgdata,dlgfig,pageNum);
end

if bRefresh
    FcnRefreshSSTool(dlgfig,dlgdata);
end


%-----------------------------------------------------------------------------------------
% FcnCalcScalingControlPositions calculates positions for all controls on scaling page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims,ctrlPos] = FcnCalcScalingControlPositions(commonGeom)

% weight of scroll bar of listbox
scrollBarWeight = 20;

strings_and_styles = { ...
    '  Var.:  ',                   'text'; ...
    '01234567890',                 'text'; ...
    'Type of outputs:',            'text'; ...
    'FLOAT32',                     'text'; ...
    'Scaling method:',             'text'; ...
    ' L1-scaling ',                'text'; ...
    'Maximum computation time',    'text'; ...
    '123456789',                   'edit'; ...
    '123456',                      'text'; ...
    'Continue',                    'pushbutton'; ...
    ' sec',                        'text'};

[ ...
    varLabelSize, ...
    numLabelSize, ...
    infoLabelSize, ...
    numTypeLabelSize, ...
    methodLabelSize, ...
    scalingLabelSize, ...
    optionsLabelSize, ...
    recEditSize, ...
    recLabelSize, ...
    buttonSize, ...
    secLabelSize] = ...
    ds_get_uicontrol_sizes(commonGeom,strings_and_styles);

widths = ...
    [varLabelSize(1) numLabelSize(1)*ones(1,8)];

[col,colWidth,colDelta,rowDelta] = ds_get_gui_columns(widths,commonGeom);

textExtent = get(commonGeom.textExtent,'Extent');
txtHeight = 0.8*textExtent(4);

% 'Output & State' groupbox and uicontrols
cx = commonGeom.figSideEdgeBuffer + commonGeom.sheetSideEdgeBuffer;
cy = commonGeom.bottomSheetOffset + ...
    commonGeom.sheetBottomEdgeBuffer;
scalingGroupboxWidth = col(end) + ...
    colWidth(end) + ...
    commonGeom.frameSideEdgeBuffer + ...
    scrollBarWeight;
scalingGroupboxHeight = ...
    8*commonGeom.editHeight + ...
    commonGeom.frameTopEdgeBuffer + ...
    commonGeom.frameBottomEdgeBuffer;
ctrlPos.scalingGroupbox =  ...
    [cx cy  scalingGroupboxWidth scalingGroupboxHeight];
% scaling listbox
cx = col(1);
cy = commonGeom.frameBottomEdgeBuffer + ...
    1.2*recEditSize(2);
scalingListboxWeight = scalingGroupboxWidth-2*commonGeom.frameSideEdgeBuffer;
scalingListboxHeight = ctrlPos.scalingGroupbox(4) ...
    - 2*txtHeight ...
    - commonGeom.frameTopEdgeBuffer ...
    - commonGeom.editHeight ...
    - commonGeom.frameBottomEdgeBuffer;
ctrlPos.scalingListbox = ...
    [cx cy scalingListboxWeight scalingListboxHeight];
% grey colored static text
cx = ctrlPos.scalingListbox(1);
cy = commonGeom.frameBottomEdgeBuffer;
ctrlPos.boldStateLabel = [cx cy varLabelSize];
% popup menu
cx = col(2);
ctrlPos.l1Popup = [cx cy colWidth(2) commonGeom.editHeight];
% edit fields
cx = col(3);
ctrlPos.minConstrEdit = [cx cy colWidth(3) commonGeom.editHeight];
cx = col(4);
ctrlPos.maxConstrEdit = [cx cy colWidth(4) commonGeom.editHeight];
% pushbuttons
cx = col(9) + colWidth(9)- buttonSize(1);
cy = commonGeom.frameBottomEdgeBuffer;
ctrlPos.l1ContinueButton = [cx cy buttonSize];
cx = cx - buttonSize(1) - commonGeom.sysButtonDelta;
ctrlPos.l1ScaleButton = [cx cy buttonSize];
% white colored static texts above listbox
cx = col(1);
cy = ctrlPos.scalingListbox(2) + ...
    ctrlPos.scalingListbox(4);
ctrlPos.varLabel = [cx cy varLabelSize(1) txtHeight];
cx = col(2);
ctrlPos.numLabel1 = [cx cy numLabelSize(1) txtHeight];
cx = col(3);
ctrlPos.numLabel2 = [cx cy numLabelSize(1) txtHeight];
cx = col(4);
ctrlPos.numLabel3 = [cx cy numLabelSize(1) txtHeight];
cx = col(5);
ctrlPos.numLabel4 = [cx cy numLabelSize(1) txtHeight];
cx = col(6);
ctrlPos.numLabel5 = [cx cy numLabelSize(1) txtHeight];
cx = col(7);
ctrlPos.numLabel6 = [cx cy numLabelSize(1) txtHeight];
cx = col(8);
ctrlPos.numLabel7 = [cx cy numLabelSize(1) txtHeight];
cx = col(9);
ctrlPos.numLabel8 = [cx cy numLabelSize(1) txtHeight];
% grey colored static texts above listbox
cx = col(3);
cy = cy + txtHeight;
limitsLabel1Width = colWidth(3) + ...
    numLabelSize(1) + ...
    colDelta/3;
ctrlPos.limitsLabel1 = [cx cy limitsLabel1Width txtHeight];
cx = col(5);
limitsLabel2Width = colWidth(5) + ...
    numLabelSize(1) + ...
    colDelta/3;
ctrlPos.limitsLabel2 = [cx cy limitsLabel2Width txtHeight];
% save columns for text pointing text in listboxes
listWidth = diff(col);
listboxGeom = [listWidth listWidth(end) colDelta/3];
ctrlPos.scalingListboxGeom = listboxGeom;

% 'System Info' groupbox and uicontrols
cx = ctrlPos.scalingGroupbox(1);
cy = ctrlPos.scalingGroupbox(2) + ...
    ctrlPos.scalingGroupbox(4) + ...
    commonGeom.textHeight;
infoGroupboxWidth = 2*infoLabelSize(1) + colDelta/2;
infoGroupboxHeight = 4*rowDelta ...
    + 6*commonGeom.textHeight ...
    + commonGeom.frameBottomEdgeBuffer ...
    + commonGeom.frameTopEdgeBuffer;
ctrlPos.infoGroupbox = ...
    [cx cy infoGroupboxWidth infoGroupboxHeight];
% static texts
cx1 = col(1);
cx2 = col(1) + infoLabelSize(1) + 0.5*colDelta;
cy1 = commonGeom.frameBottomEdgeBuffer;
for k = 2:6
    eval(['cy' num2str(k) ' = cy' num2str(k-1) ...
        ' + infoLabelSize(2) + 0.6*rowDelta;']);
end
ctrlPos.stabilityLabel = [cx1 cy6 infoLabelSize];
ctrlPos.stabilityInfoLabel = [cx2 cy6 numTypeLabelSize];
ctrlPos.numInputsLabel = [cx1 cy5 infoLabelSize];
ctrlPos.numInputsInfoLabel = [cx2 cy5 numTypeLabelSize];
ctrlPos.numStatesLabel = [cx1 cy4 infoLabelSize];
ctrlPos.numStatesInfoLabel = [cx2 cy4 numTypeLabelSize];
ctrlPos.typeStatesLabel = [cx1 cy3 infoLabelSize];
ctrlPos.typeStatesInfoLabel = [cx2 cy3 numTypeLabelSize];
ctrlPos.numOutputsLabel = [cx1 cy2 infoLabelSize];
ctrlPos.numOutputsInfoLabel = [cx2 cy2 numTypeLabelSize];
ctrlPos.typeOutputsLabel = [cx1 cy1 infoLabelSize];
ctrlPos.typeOutputsInfoLabel = [cx2 cy1 numTypeLabelSize];

% 'Scaling Options' groupbox and uicontrols
cx = ctrlPos.infoGroupbox(1) ...
    + ctrlPos.infoGroupbox(3) ...
    + colDelta;
cy = ctrlPos.infoGroupbox(2);
optionsGroupboxWidth = optionsLabelSize(1) + recEditSize(1) + secLabelSize(1) + colDelta;
optionsGroupboxHeight = infoGroupboxHeight;
ctrlPos.optionsGroupbox = ...
    [cx cy optionsGroupboxWidth optionsGroupboxHeight];
% static texts and edit fields
cx = col(1);
for k = 2:5
    eval(['cy' num2str(k) ' = cy' num2str(k-1) ...
        ' + infoLabelSize(2) + 1.7*rowDelta;']);
end
ctrlPos.methodLabel = [cx cy5 methodLabelSize];
ctrlPos.convTolLabel = [cx cy4 optionsLabelSize];
ctrlPos.maxRecLabel = [cx cy3 optionsLabelSize];
ctrlPos.actRecLabel = [cx cy2 optionsLabelSize];
ctrlPos.contLabel = [cx cy1 optionsLabelSize];
cx = cx + optionsLabelSize(1) + 0.5*colDelta;
ctrlPos.methodInfoLabel = [cx cy5 scalingLabelSize];
ctrlPos.convTolEdit = [cx cy4 recEditSize];
ctrlPos.percLabel = [sum(ctrlPos.convTolEdit([1 3])) cy4 secLabelSize];
ctrlPos.maxTimeEdit = [cx cy3 recEditSize];
ctrlPos.secLabel = [sum(ctrlPos.convTolEdit([1 3])) cy3 secLabelSize];
ctrlPos.numRecInfoLabel = [cx cy2 recLabelSize];
ctrlPos.contInfoLabel = [cx cy1 recLabelSize];

% 'Input' groupbox and uicontrols
cx = ctrlPos.optionsGroupbox(1) ...
    + ctrlPos.optionsGroupbox(3) ...
    + colDelta;
cy = ctrlPos.optionsGroupbox(2);
inputGroupboxWidth = sum(ctrlPos.scalingGroupbox([1 3])) - cx;
inputGroupboxHeight = infoGroupboxHeight;
ctrlPos.inputGroupbox = ...
    [cx cy inputGroupboxWidth inputGroupboxHeight];
% input listbox
cx = col(1);
cy = commonGeom.frameBottomEdgeBuffer + ...
    1.2*recEditSize(2);
inputListboxWeight = inputGroupboxWidth - 2*commonGeom.frameSideEdgeBuffer;
inputListboxHeight = ctrlPos.inputGroupbox(4) ...
    - 2*txtHeight ...
    - commonGeom.frameTopEdgeBuffer ...
    - commonGeom.editHeight ...
    - commonGeom.frameBottomEdgeBuffer;
ctrlPos.inputListbox = ...
    [cx cy inputListboxWeight inputListboxHeight];
% white colored static texts above listbox
cx = col(1);
cy = ctrlPos.inputListbox(2) + ...
    ctrlPos.inputListbox(4);
ctrlPos.inputLabel = [cx cy varLabelSize(1) txtHeight];
ctrlPos.maxInputLabel = [col(2) cy numLabelSize(1) txtHeight];
ctrlPos.minInputLabel = [col(3) cy numLabelSize(1) txtHeight];
% save columns for text pointing text in listboxes
listWidth = diff(col(1:3));
listboxGeom = [listWidth listWidth(end) colDelta/3];
ctrlPos.inputListboxGeom = listboxGeom;
% grey colored static texts
cx = col(2);
cy = cy + txtHeight;
limitsLabel3Width = colWidth(2) + ...
    numLabelSize(1) + ...
    colDelta/3;
ctrlPos.limitsLabel3 = [cx cy limitsLabel3Width txtHeight];
cx = col(1);
cy = commonGeom.frameBottomEdgeBuffer;
ctrlPos.boldInputLabel = [cx cy varLabelSize(1) varLabelSize(2)];
% edit fields
cx = col(2);
ctrlPos.minInputEdit = [cx cy numLabelSize(1) commonGeom.editHeight];
cx = col(3);
ctrlPos.maxInputEdit = [cx cy numLabelSize(1) commonGeom.editHeight];

width = ...
    2*commonGeom.frameSideEdgeBuffer + ...
    scalingGroupboxWidth;

height = ...
    commonGeom.sheetTopEdgeBuffer + ...
    ctrlPos.infoGroupbox(4) + ...
    commonGeom.textHeight + ...
    ctrlPos.scalingGroupbox(4) + ...
    commonGeom.sheetBottomEdgeBuffer;

sheetDims = [width height];


%-----------------------------------------------------------------------------------------
% FcnUpdateScalingPage updates control actions of scaling page
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageNum     number of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnUpdateScalingPage(dlgdata,dlgfig,pageNum)

Children = dlgdata.pageData{pageNum}.children;

% check if initial condition has changed
oldInitial = tl_resolve(dlgdata.data.state.initial, dlgdata.pageData{1}.model);
newInitial = tl_resolve(dlgdata.pageData{pageNum}.origData.state.initial, dlgdata.pageData{1}.model);
if any(oldInitial ~= newInitial) && dlgdata.toolData.bIsScaled
    ds_error_msg({'You have modified the initial condition.', ...
        'The scaling results will be cleared.'}, ...
        'Title','State-Space Scaling Tool', ...
        'PrintMessage','no', ...
        'RegisterMessage','no');
    dlgdata = FcnInitScalingData(dlgdata);
    if ishandle(dlgdata.toolfig)
        delete(dlgdata.toolfig);
        dlgdata.toolfig = -1;
    end
end

%% "System Info" groupbox
toolData = dlgdata.toolData;
origData = dlgdata.pageData{pageNum}.origData;

% check stability of the discrete state space system
Ad = tl_resolve(origData.amatrix.value, dlgdata.pageData{1}.model);
if isempty(Ad)
    stability = 'stable';
else
    eigen_vals = eig(Ad);
    mag_vals   = abs(eigen_vals);
    if all(mag_vals < 1)
        stability = 'stable';
    else
        stability = 'instable';
    end
end
% set sytem info data
set(Children.stabilityInfoLabel,'String',stability);
numStates = size(Ad, 1);
set(Children.numStatesInfoLabel,'String',num2str(numStates));
Dd = tl_resolve(origData.dmatrix.value, dlgdata.pageData{1}.model);
numInputs = size(Dd, 2);
set(Children.numInputsInfoLabel,'String',num2str(numInputs));
numOutputs = size(Dd, 1);
set(Children.numOutputsInfoLabel,'String',num2str(numOutputs));
if numInputs == 0  % if system is a gain matrix
    typeStates = '---';
else
    typeStates = origData.state.type;
end
if numOutputs == 0
    typeOutputs = '---';
else
    typeOutputs = origData.output.type;
end
set(Children.typeStatesInfoLabel,'String',typeStates);
set(Children.typeOutputsInfoLabel,'String',typeOutputs);

%% "Scaling Options" groupbox
options = toolData.options;
if numInputs
    set(Children.convTolEdit,'String',options.convTol);
    set(Children.maxTimeEdit,'String',options.maxTime);
    set(Children.numRecInfoLabel,'String',options.numRecs);
    set(Children.contInfoLabel,'String',options.contNum);
end

%% "Input" groupbox
u_min = toolData.input.min;
u_max = toolData.input.max;
inputListboxStr = cell('',numInputs);
for k = 1 : numInputs
    u_min_str = FcngetStr(u_min(k));
    u_max_str = FcngetStr(u_max(k));
    str_cell = {['u(' num2str(k) ')'],u_min_str,u_max_str};
    str = FcnallignStrings(dlgfig,str_cell, ...
        dlgdata.pageData{pageNum}.inputListboxGeom);
    inputListboxStr{k} = str;
end
set(Children.inputListbox,'String',inputListboxStr);

%% 'Output & State' groupbox
% "Continue" and "Plot Results" button
bIsScaled = dlgdata.toolData.bIsScaled;
userDataPlotResults = get(dlgdata.SystemButtons.PlotResults, 'UserData');
if bIsScaled
    if isempty(dlgdata.pageData{pageNum}.l1_strct)  % if only gain matrix has been scaled
        enableContinueButton = 'off';
        enablePlotButton     = 'off';
        cDataPlotResults = userDataPlotResults.cDataDisabled;
        converge_y = [];
    else
        converge_x = dlgdata.pageData{pageNum}.l1_strct.converge_x;
        converge_y = dlgdata.pageData{pageNum}.l1_strct.converge_y;
        enableContinueButton = 'on';
        enablePlotButton = 'on';
        cDataPlotResults = userDataPlotResults.cDataEnabled;
    end
else
    enableContinueButton = 'off';
    enablePlotButton = 'off';
    cDataPlotResults = userDataPlotResults.cDataDisabled;
end
set(Children.l1ContinueButton,'Enable',enableContinueButton);
set(dlgdata.SystemButtons.PlotResults, ...
    'CData', cDataPlotResults, ...
    'Enable',   enablePlotButton);

% "Scale" button
bL1 = toolData.bL1;
if numInputs
    idx = find(isnan(u_min) | isnan(u_max), 1);
    if isempty(idx) &&  any(bL1)
        enablel1ScaleButton = 'on';
    else
        enablel1ScaleButton = 'off';
    end
else
    if any(bL1)
        enablel1ScaleButton = 'on';
    else
        enablel1ScaleButton = 'off';
    end
end
set(Children.l1ScaleButton,'Enable',enablel1ScaleButton);

% popup menu and edit fields
v = get(Children.scalingListbox,'Value');
FcnsetCtrlFields(dlgdata,pageNum,'scalingListbox',v);
if bL1(v)
    v = 1;
else
    v = 2;
end
set(Children.l1Popup,'Value',v);
if numInputs
    v = get(Children.inputListbox,'Value');
    FcnsetCtrlFields(dlgdata,pageNum,'inputListbox',v);
end

bConstr = toolData.bConstr;
info.keeptype   = dlgdata.data.autoscaling.keepoutputtype;
info.keepoffset = dlgdata.data.autoscaling.keepoutputoffset;

% calculate and write data into structure
if numStates > 0
    idx = find(bL1(1:numStates));
    dlgdata.data.state = origData.state;
    % expand tool data, if necessary
    if isequal(dlgdata.data.state.width, -1)
        dlgdata.data.state.width = numStates;
        dlgdata.data.state.lsb(1:numStates) = dlgdata.data.state.lsb;
        dlgdata.data.state.arb(1:numStates) = dlgdata.data.state.arb;
        dlgdata.data.state.offset(1:numStates) = dlgdata.data.state.offset;
        dlgdata.data.state.min(1:numStates) = dlgdata.data.state.min;
        dlgdata.data.state.max(1:numStates) = dlgdata.data.state.max;
    end
    dlgdata.data.state.min(idx) = toolData.state.min(idx);
    dlgdata.data.state.max(idx) = toolData.state.max(idx);
    % calculate scaling parameters
    [dlgdata.data.state, ...
        dlgdata.toolData.state.min_impl, ...
        dlgdata.toolData.state.max_impl, ...
        dlgdata.toolData.successStates] = FcncalcVars(dlgdata.data.state,info,numStates);
    state = dlgdata.data.state;
    x_min_impl = dlgdata.toolData.state.min_impl;
    x_max_impl = dlgdata.toolData.state.max_impl;
    % create cell array for listbox text
    scalingListboxStr = cell('',numStates);
    for k = 1 : numStates
        x_min_str = FcngetStr(state.min(k));
        x_max_str = FcngetStr(state.max(k));
        if bL1(k)
            l1_str = 'yes';
        else
            l1_str = 'no';
            if bConstr(k)
                x_min_str = (['[' x_min_str ']']);
                x_max_str = (['[' x_max_str ']']);
            end
        end
        x_min_impl_str = FcngetStr(x_min_impl(k));
        x_max_impl_str = FcngetStr(x_max_impl(k));
        if state.arb(k)
            lsb(k)  = state.lsb(k);
            lsb_str = FcngetStr(lsb(k));
        else
            lsb(k)  = log2(state.lsb(k));
            lsb_str = ['2 ^ ' num2str(lsb(k))];
        end
        if isinf(lsb(k)) ...
                || isnan(state.min(k)) ...
                || isnan(state.max(k)) ...
                || isnan(x_min_impl(k)) ...
                || isnan(x_max_impl(k))
            lsb_str    = FcngetStr(Inf);
            offset_str = FcngetStr(Inf);
        else
            offset_str = FcngetStr(state.offset(k));
        end
        if bIsScaled
            if all(converge_x(k,:))
                conv_str = 'yes';
            else
                conv_str = 'no';
            end
        else
            conv_str = [];
        end
        str_cell = {['x(' num2str(k) ')'],l1_str,x_min_str,x_max_str, ...
            x_min_impl_str,x_max_impl_str,lsb_str,offset_str,conv_str};
        str = FcnallignStrings(dlgfig,str_cell,dlgdata.pageData{pageNum}.scalingListboxGeom);
        scalingListboxStr{k} = str;
    end
end

if numOutputs > 0
    idx = find(bL1(numStates+1:numStates+numOutputs));
    dlgdata.data.output = origData.output;
    % expand tool data, if necessary
    if isequal(dlgdata.data.output.width, -1)
        dlgdata.data.output.width = numOutputs;
        dlgdata.data.output.lsb(1:numStates) = dlgdata.data.output.lsb;
        dlgdata.data.output.arb(1:numStates) = dlgdata.data.output.arb;
        dlgdata.data.output.offset(1:numStates) = dlgdata.data.output.offset;
        dlgdata.data.output.min(1:numStates) = dlgdata.data.output.min;
        dlgdata.data.output.max(1:numStates) = dlgdata.data.output.max;
    end
    dlgdata.data.output.min(idx) = toolData.output.min(idx);
    dlgdata.data.output.max(idx) = toolData.output.max(idx);
    % calculate scaling parameters
    [dlgdata.data.output, ...
        dlgdata.toolData.output.min_impl, ...
        dlgdata.toolData.output.max_impl, ...
        dlgdata.toolData.successOutputs] = FcncalcVars(dlgdata.data.output,info, numOutputs);
    output = dlgdata.data.output;
    y_min_impl = dlgdata.toolData.output.min_impl;
    y_max_impl = dlgdata.toolData.output.max_impl;
    % create cell array for listbox text
    scalingListboxStr(numStates+1:numStates+numOutputs) = {[]};
    for j = 1:numOutputs
        y_min_str = FcngetStr(output.min(j));
        y_max_str = FcngetStr(output.max(j));
        if bL1(numStates+j)
            l1_str = 'yes';
        else
            l1_str = 'no';
            if bConstr(numStates+j)
                y_min_str = (['[' y_min_str ']']);
                y_max_str = (['[' y_max_str ']']);
            end
        end
        y_min_impl_str = FcngetStr(y_min_impl(j));
        y_max_impl_str = FcngetStr(y_max_impl(j));
        if output.arb(j)
            lsb(j)  = output.lsb(j);
            lsb_str = FcngetStr(lsb(j));
        else
            lsb(j)  = log2(output.lsb(j));
            lsb_str = ['2 ^ ' num2str(lsb(j))];
        end
        if isinf(lsb(j)) ...
                || isnan(output.min(j)) ...
                || isnan(output.max(j)) ...
                || isnan(y_min_impl(j)) ...
                || isnan(y_max_impl(j))
            lsb_str    = FcngetStr(Inf);
            offset_str = FcngetStr(Inf);
        else
            offset_str = FcngetStr(output.offset(j));
        end
        if bIsScaled
            if isempty(converge_y)
                conv_str = '';
            else
                if all(converge_y(j,:))
                    conv_str = 'yes';
                else
                    conv_str = 'no';
                end
            end
        else
            conv_str = [];
        end
        str_cell = {['y(' num2str(j) ')'],l1_str,y_min_str,y_max_str, ...
            y_min_impl_str,y_max_impl_str,lsb_str,offset_str,conv_str};
        str = FcnallignStrings(dlgfig,str_cell,dlgdata.pageData{pageNum}.scalingListboxGeom);
        scalingListboxStr{numStates+j} = str;
    end
end

set(Children.scalingListbox,'String',scalingListboxStr);


%-----------------------------------------------------------------------------------------
% FcnInitScalingData initializes scaling data (states&outputs)
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnInitScalingData(dlgdata)

Ad = tl_resolve(dlgdata.data.amatrix.value, dlgdata.pageData{1}.model);
numStates = size(Ad, 1);
Dd = tl_resolve(dlgdata.data.dmatrix.value, dlgdata.pageData{1}.model);
numInputs = size(Dd, 2);
numOutputs = size(Dd, 1);

u_min = dlgdata.toolData.input.min;
u_max = dlgdata.toolData.input.max;
% make sure that numel(u) = numInputs
u_min(numel(u_min)+1:numInputs) = NaN;
u_max(numel(u_max)+1:numInputs) = NaN;
u_min(numInputs+1:end) = [];
u_max(numInputs+1:end) = [];

x_min = dlgdata.data.state.min;
x_max = dlgdata.data.state.max;
% make sure that numel(x) = numStates
if isequal(dlgdata.data.state.width, -1)
    x_min(1:numStates) = x_min;
    x_max(1:numStates) = x_max;
end

y_min = dlgdata.data.output.min;
y_max = dlgdata.data.output.max;
% make sure that numel(x) = numStates
if isequal(dlgdata.data.output.width, -1)
    y_min(1:numOutputs) = y_min;
    y_max(1:numOutputs) = y_max;
end

bL1 = zeros(size([x_min y_min]));
idx_x = find(~isfinite(x_min) & ~isfinite(x_max));
bL1(idx_x) = 1;
idx_y = find(~isfinite(y_min) & ~isfinite(y_max));
bL1(length(x_min)+idx_y) = 1;
% write data into tooldata structure
dlgdata.toolData.input.min  = u_min;
dlgdata.toolData.input.max  = u_max;
dlgdata.toolData.state.min  = -NaN*ones(1,length(x_min));
dlgdata.toolData.state.max  =  NaN*ones(1,length(x_max));
dlgdata.toolData.output.min = -NaN*ones(1,length(y_min));
dlgdata.toolData.output.max =  NaN*ones(1,length(y_max));
dlgdata.toolData.bL1        = bL1;
dlgdata.toolData.bConstr    = ~bL1;
dlgdata.toolData.bIsScaled  = 0;


%-----------------------------------------------------------------------------------------
% FcnChkOffsetAndType check conststency of scaling parameters (Offset & Datatype)
%
% INPUT ARGUMENTS
%   dlgdata         dialog data
%   msgflag         flag =1, if message should be displayed, =0 otherwise
%
% OUTPUT ARGUMENTS
%   ok              flag =1, if ok, =0 otherwise
%-----------------------------------------------------------------------------------------
function ok = FcnChkOffsetAndType(dlgdata,msgFlag)

ok = 1;
toolData = dlgdata.toolData;

typeCell = {'UInt8' 'UInt16' 'UInt32'};

Ad = tl_resolve(dlgdata.data.amatrix.value, dlgdata.pageData{1}.model);
if ~isempty(Ad)     % number of states >0
    % check if offset is unfrozen for UINT data type
    if any(strcmp(dlgdata.data.state.type,typeCell))
        idx = find(all([~toolData.successStates; ...
            dlgdata.data.autoscaling.keepoutputoffset]));
        if ~isempty(idx)
            if length(idx) > 3
                idxStr = [num2str(idx(1:3)) ' ...'];
            else
                idxStr = num2str(idx);
            end
            msgStr = ['The constrained limits of x(' idxStr ')', ...
                ' cannot be implemented with unsigned data type' ...
                ' and frozen offset !'];
            if msgFlag
                ds_error_msg(msgStr, ...
                    'Title','State-Space Scaling Tool', ...
                    'PrintMessage','no', ...
                    'RegisterMessage','no');
            end
            set(dlgdata.SystemButtons.StatusLabel,'String',msgStr, ...
                'ForegroundColor','r');
            ok = 0;
        end
    end
end

Cd = tl_resolve(dlgdata.data.cmatrix.value, dlgdata.pageData{1}.model);
Dd = tl_resolve(dlgdata.data.dmatrix.value, dlgdata.pageData{1}.model);
if ~isempty(Cd) && ~isempty(Dd)     % number of outputs >0
    % check if offset is unfrozen for UINT data type
    if any(strcmp(dlgdata.data.output.type,typeCell))
        idx = find(all([~toolData.successOutputs; ...
            dlgdata.data.autoscaling.keepoutputoffset]));
        if ~isempty(idx)
            if length(idx) > 3
                idxStr = [num2str(idx(1:3)) ' ...'];
            else
                idxStr = num2str(idx);
            end
            msgStr = ['The constrained limits of y(' idxStr ')', ...
                ' cannot be implemented with unsigned data type' ...
                ' and frozen offset !'];
            if msgFlag
                ds_error_msg(msgStr, ...
                    'Title','State-Space Scaling Tool', ...
                    'PrintMessage','no', ...
                    'RegisterMessage','no');
            end
            set(dlgdata.SystemButtons.StatusLabel,'String',msgStr, ...
                'ForegroundColor','r');
            ok = 0;
        end
    end
end


%-----------------------------------------------------------------------------------------
% FcnchkInput checks string of edit field
%
% INPUT ARGUMENTS
%   h           handle of edit control
%   entryType   type
%   defaultVal  default value
%
% OUTPUT ARGUMENTS
%   inputVal    value
%   ok          flag =1, if ok, =0 otherwise
%-----------------------------------------------------------------------------------------
function [inputVal,ok] = FcnchkInput(h,entryType,defaultVal)

inputValStr = get(h,'String');
if nargin < 3
    defaultVal = [];
end

ok = 1;

switch entryType
    case 'double'
        if isempty(inputValStr) ...
                || (isa(inputValStr,'char') && strcmp(inputValStr,''))
            inputVal = NaN;
        else
            inputVal = str2double(inputValStr);
            if ~isa(inputVal,'double') ...
                    || isempty(inputVal) ...
                    || length(inputVal) > 1 ...
                    || isinf(inputVal)
                inputVal = defaultVal;
                ok = 0;
            end
        end
end


%-----------------------------------------------------------------------------------------
% FcnallignStrings alligns strings for listbox
%
% INPUT ARGUMENTS
%   dlgfig          dialog handle
%   str_cell        cell string
%   listboxData     current listbox data
%
% OUTPUT ARGUMENTS
%   str             string
%-----------------------------------------------------------------------------------------
function str = FcnallignStrings(dlgfig,str_cell,listboxData)

% consider offset
listboxData(end-1) = listboxData(end-1)-1;

% get number of str
str_num = length(str_cell);
% get number of columns of listbox
col_num = length(listboxData)-1;
if col_num ~= str_num
    error('Number of strings and listbox columns do not agree !');
end

% create temporary uicontrol in gui
txt = uicontrol('Parent',   dlgfig, ...
    'FontName', 'Arial', ...
    'Style',    'text', ...
    'Visible',  'off', ...
    'Position', [0 0 1 1]);

colDelta = listboxData(end);
tab_str1 = ' ';
set(txt,'String',tab_str1);
tab_ext1 = get(txt,'Extent');
tab_str2 = '  ';
set(txt,'String',tab_str2);
tab_ext2 = get(txt,'Extent');
tab_pix = tab_ext2(3) - tab_ext1(3);

str = str_cell{1};
tmp_str = '';
% get pixel sizes of the strings and calculate missing tabs
for k = 1:str_num
    set(txt,'String',str);
    ext = get(txt,'extent');
    str_pix = ext(3);
    listData = sum(listboxData(1:k)) - colDelta;
    diff_pix = listData - str_pix;
    num_tab = floor(diff_pix/tab_pix);
    num_tabs = num_tab + length(str_cell{k});
    str_cell{k} = sprintf(['%' num2str(num_tabs) 's'],str_cell{k});
    tmp_str = [tmp_str str_cell{k}];
    if k < str_num
        str = [tmp_str str_cell{k+1}];
    else
        str = tmp_str;
    end
end

% delete temporary uicontrol from gui
delete(txt);


%--------------------------------------------------------------------------
% FcngetStr get formated strings for listbox
%
% INPUT ARGUMENTS
%   num         value
%
% OUTPUT ARGUMENTS
%   num_str     string
%--------------------------------------------------------------------------
function num_str = FcngetStr(num)

num_str = sprintf('%0.5g',num);
if ~isfinite(num)
    num_str = '--- ';
end


%--------------------------------------------------------------------------
% FcncalcVars calculate implemented limits, lsb's and offsets
%
% INPUT ARGUMENTS
%   data        data set of variable
%   info        keep information
%   width       current variable width
%
% OUTPUT ARGUMENTS
%   data        modified data set of variable
%   min_impl    vector of minima
%   max_impl    vector of maxima
%   success     success vector
%--------------------------------------------------------------------------
function [data,min_impl,max_impl,success] = FcncalcVars(data,info,width)

if width > 0
    success = zeros(1,width);
    offset = zeros(1,width);
    lsb = ones(1,width);
    min_impl = zeros(1,width);
    max_impl = zeros(1,width);
    for k = 1 : width
        scData = set_elemdata(data, k, []);
        scData.type = data.type;
        [scData,success(k)] = tl_scale(scData, 0, info);
        if success(k)
            [maxint,minint] = tl_int_bounds(scData.type);
            offset(k)   = scData.offset;
            lsb(k)      = scData.lsb;
            min_impl(k) = lsb(k) * minint + offset(k);
            max_impl(k) = lsb(k) * maxint + offset(k);
        else
            min_impl(k) = NaN;
            max_impl(k) = NaN;
            offset(k)   = data.offset(k);
            lsb(k)      = data.lsb(k);
        end
    end
    data.lsb    = lsb;
    data.offset = offset;
else
    min_impl = [];
    max_impl = [];
    success  = 0;
end


%-----------------------------------------------------------------------------------------
% FcnsetCtrlFields writes data into edit fields below of scaling listbox
%
% INPUT ARGUMENTS
%   dlgdata         current dialog data
%   pageNum         page number
%   listboxStr      current listbox data
%   v               number
%
% OUTPUT ARGUMENTS
%   - / -
%-----------------------------------------------------------------------------------------
function FcnsetCtrlFields(dlgdata,pageNum,listboxStr,v)

% numStates = dlgdata.data.state.width;
Ad = tl_resolve(dlgdata.data.amatrix.value, dlgdata.pageData{1}.model);
numStates = size(Ad, 1);
Children  = dlgdata.pageData{pageNum}.children;
bL1       = dlgdata.toolData.bL1;

switch listboxStr
    case 'scalingListbox'
        
        colorStr = 'k';
        bWarning = 0;
        
        if length(v) == 1
            if v <= numStates
                strctStr = 'state';
                i = v;
                varStr   = ['x(' num2str(i) '):'];
            else
                strctStr = 'output';
                i = v - numStates;
                varStr   = ['y(' num2str(i) '):'];
            end
            if bL1(v)
                eval(['ll = dlgdata.toolData.' strctStr '.min(i);']);
                eval(['ul = dlgdata.toolData.' strctStr '.max(i);']);
            else
                eval(['ll = dlgdata.data.' strctStr '.min(i);']);
                eval(['ul = dlgdata.data.' strctStr '.max(i);']);
            end
            if ll > ul
                bWarning = 1;
            end
            if isnan(ll) || isinf(ll)
                ll_str = [];
            else
                ll_str = FcngetStr(ll);
            end
            if isnan(ul) || isinf(ul)
                ul_str = [];
            else
                ul_str = FcngetStr(ul);
            end
            if bL1(v);
                popupVal = 1;
            else
                popupVal = 2;
            end
            set(Children.l1Popup,'Value',popupVal);
        elseif isempty(v)
            ll_str = [];
            ul_str = [];
            varStr = [];
        else
            vx = v(v <= numStates);
            vy = v(v > numStates);
            indL1 = find(dlgdata.toolData.bL1);
            if ~isempty(vx)
                idx = intersect(indL1,vx);
                if ~isempty(idx)
                    x_min(idx) = dlgdata.toolData.state.min(idx);
                    x_max(idx) = dlgdata.toolData.state.max(idx);
                end
                idx = setdiff(vx,indL1);
                if ~isempty(idx)
                    x_min(idx) = dlgdata.data.state.min(idx);
                    x_max(idx) = dlgdata.data.state.max(idx);
                end
                if any(x_min > x_max)
                    idxWarn = find(x_min > x_max);
                    ll_str = FcngetStr(x_min(idxWarn(1)));
                    ul_str = FcngetStr(x_max(idxWarn(1)));
                    varStr = ['x(' num2str(idxWarn(1)) ')'];
                    bWarning = 1;
                end
            else
                x_min = [];
                x_max = [];
            end
            if ~isempty(vy)
                idx = intersect(indL1,vy);
                if ~isempty(idx)
                    idx = idx-numStates;
                    y_min(idx) = dlgdata.toolData.output.min(idx);
                    y_max(idx) = dlgdata.toolData.output.max(idx);
                end
                idx = setdiff(vy,indL1);
                if ~isempty(idx)
                    idx = idx-numStates;
                    y_min(idx) = dlgdata.data.output.min(idx);
                    y_max(idx) = dlgdata.data.output.max(idx);
                end
                if any(y_min > y_max)
                    idxWarn = find(y_min > y_max);
                    ll_str = FcngetStr(y_min(idxWarn(1)));
                    ul_str = FcngetStr(y_max(idxWarn(1)));
                    varStr = ['y(' num2str(idxWarn(1)) ')'];
                    bWarning = 1;
                end
            else
                y_min = [];
                y_max = [];
            end
            if ~bWarning
                minVec = [x_min(vx) y_min(vy-numStates)];
                if any(diff(minVec))
                    ll_str = [];
                else
                    ll_str = FcngetStr(minVec(1));
                end
                maxVec = [x_max(vx) y_max(vy-numStates)];
                if any(diff(maxVec))
                    ul_str = [];
                else
                    ul_str = FcngetStr(maxVec(1));
                end
                varStr = [];
            else
                v = idxWarn(1);
            end
        end
        if bWarning && ~isempty(v)
            colorStr = 'r';
            set(Children.scalingListbox,'Value',v);
        end
        set(Children.minConstrEdit,'String',ll_str,'ForeGroundColor',colorStr);
        set(Children.maxConstrEdit,'String',ul_str,'ForeGroundColor',colorStr);
        set(Children.boldStateLabel,'String',varStr);
        
    case 'inputListbox'
        
        colorStr = 'k';
        
        u_min = dlgdata.toolData.input.min;
        u_max = dlgdata.toolData.input.max;
        if isnan(u_min(v(1))) || isinf(u_min(v(1)))
            min_str = [];
        else
            min_str = FcngetStr(u_min(v(1)));
        end
        if isnan(u_max(v(1))) || isinf(u_max(v(1)))
            max_str = [];
        else
            max_str = FcngetStr(u_max(v(1)));
        end
        if length(v) > 1
            if any(diff(u_min(v)))
                min_str = [];
            end
            if any(diff(u_max(v)))
                max_str = [];
            end
            u_str = [];
            if all(u_min(v) > u_max(v))
                colorStr = 'r';
            end
        else
            if isnan(u_min)
                min_str = [];
            end
            if isnan(u_max)
                max_str = [];
            end
            u_str = ['u(' num2str(v) '):'];
            if u_min(v) > u_max(v)
                colorStr = 'r';
            end
        end
        
        set(Children.minInputEdit,'String',min_str,'ForeGroundColor',colorStr);
        set(Children.maxInputEdit,'String',max_str,'ForeGroundColor',colorStr);
        set(Children.boldInputLabel,'String',u_str);
        
end


%-----------------------------------------------------------------------------------------
% FcnsetPlotData prepares structure for plot figure
%
% INPUT ARGUMENTS
%   dlgdata         current dialog data
%
% OUTPUT ARGUMENTS
%   data            plot data
%-----------------------------------------------------------------------------------------
function data = FcnsetPlotData(dlgdata)

% get popup values of plot figure
if dlgdata.toolfig == -1
    data.popupValue = [1 1];
elseif ~ishandle(dlgdata.toolfig)
    data.popupValue = dlgdata.toolData.popupValue;
end
data.Ad = dlgdata.data.amatrix.value;
data.Bd = dlgdata.data.bmatrix.value;
data.Cd = dlgdata.data.cmatrix.value;
data.Dd = dlgdata.data.dmatrix.value;
Ad = tl_resolve(dlgdata.data.amatrix.value, dlgdata.pageData{1}.model);
Dd = tl_resolve(dlgdata.data.dmatrix.value, dlgdata.pageData{1}.model);
data.numInputs = size(Dd, 2);
data.numStates = size(Ad, 1);
data.numOutputs = size(Dd, 1);
% calculate lsb and offset for tool data
dlgdata.state.min  = dlgdata.toolData.state.min;
dlgdata.state.max  = dlgdata.toolData.state.max;
dlgdata.output.min = dlgdata.toolData.output.min;
dlgdata.output.max = dlgdata.toolData.output.max;
info.keeptype   = dlgdata.data.autoscaling.keepoutputtype;
info.keepoffset = dlgdata.data.autoscaling.keepoutputoffset;
[data.state,x_min_impl,x_max_impl] = FcncalcVars(dlgdata.data.state, info, data.numStates);
data.state.min_impl = x_min_impl;
data.state.max_impl = x_max_impl;
[data.output,y_min_impl,y_max_impl] = FcncalcVars(dlgdata.data.output, info, data.numOutputs);
data.output.min_impl = y_min_impl;
data.output.max_impl = y_max_impl;
data.state.type    = dlgdata.data.state.type;
data.output.type   = dlgdata.data.output.type;
data.l1_strct      = dlgdata.pageData{1}.l1_strct;
data.options       = dlgdata.toolData.options;


%-----------------------------------------------------------------------------------------
% FcnRefreshSSTool refreshs sstool plot figure window
%
% INPUT ARGUMENTS
%   dlgfig          current dialog handle
%   dlgdata         current dialog data
%
% OUTPUT ARGUMENTS
%   - / -
%-----------------------------------------------------------------------------------------
function FcnRefreshSSTool(dlgfig,dlgdata)

pageNum = 1;
toolfig = dlgdata.toolfig;

if ishandle(toolfig)
    set(dlgfig,'Pointer','watch');
    data = FcnsetPlotData(dlgdata);
    name = get_param(dlgdata.pageData{pageNum}.model,'Name');
    tl_sstool('refresh',data,name,toolfig);
    set(dlgfig,'Pointer','arrow');
end
